#coding:utf-8
from json import JSONEncoder
from mongoengine.base import BaseDocument

from mongoengine import*

connect("user")

class userlist(Document):
    name = StringField()
    age = IntField()
    birth = StringField()
    sex = IntField()
    addr = StringField()
    aid = IntField()
def get(name):
    if name:
        a=userlist.objects(name=name).all() #all method remove fields that class userlist not includs
    else:
        a=userlist.objects().all() #all method remove fields that class userlist not includs
#print a
    res=[]
    for i in a:
        res.append({
               "id":i.aid,
               "name":i.name,
               "age":i.age,
               "birth":i.birth,
               "sex":i.sex,
               "addr":i.addr
              })
    return res
#print res
def getUserList(name=""):
    return get(name)

def removeUser(id):
    try:
        res=userlist.objects(aid=id)
    except Exception:pass
    if res:
        res.delete()
        print(u"还剩"+str(userlist.objects().count()))
        return True
    else:return False
    
def addUser(name,sex,addr,age,birth):    
    a=userlist(name=name)
    if not sex:a.sex=1
    else:a.sex=sex
    if not addr:a.addr="未知"
    else: a.addr=addr
    if not age:a.age=0
    else: a.age=age
    if not birth:a.birth="1900-01-01"
    else: a.birth=birth
    a.aid=int(userlist.objects().count())+1
    try:
        a.save()
        return True
    except Exception:return False
   
def userEdit(name,sex,addr,age,birth,id):
    #aid=userlist.objects()[id-1].aid
    a=userlist.objects(aid=id)
    print "update:"
    print a[0].name
    if not a:return False
    else:
        try:
            name=name if name else "无名氏"
            sex=sex if sex else 1
            addr=addr if addr else "用户未填"
            age=age if age else 0
            birth=birth if birth else "未知"
            a[0].update(
                   name=name,
                   sex=sex,
                   addr=addr,
                   age=age,
                   birth=birth
                   )
            return True
        except Exception,e:
            print e
            return False         
#        if not sex:a[0].sex=1
#        else:a.sex=sex
#        if not addr:a[0].addr="未知"
#        else: a[0].addr=addr
#        if not age:a[0].age=0
#        else: a[0].age=age
#        if not birth:a[0].birth="1900-01-01"
#        else: a[0].birth=birth
#        try:
#           a[0].save()
#           return True
#        except Exception,err:
#           print err
#           return False
#        try:
#            a[0].update()
#            return True
#        except Exception,e:
#            print e
#            return False
 
